﻿using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace Core.Infrastructure.CommandExtensions
{
    public class UserControlMouseMove
    {
       private static readonly DependencyProperty UserControlMouseMoveCommandBehaviorProperty = DependencyProperty.RegisterAttached(
            "UserControlMouseMoveCommandBehavior",
            typeof(UserControlMouseMoveCommandBehavior),
            typeof(UserControlMouseMove),
            null);

        public static readonly DependencyProperty CommandProperty = DependencyProperty.RegisterAttached(
            "Command",
            typeof(ICommand),
            typeof(UserControlMouseMove),
            new PropertyMetadata(OnSetCommandCallback));

        public static void SetCommand(UserControl userControl, ICommand command)
        {
            userControl.SetValue(CommandProperty, command);
        }

        public static ICommand GetCommand(UserControl userControl)
        {
            return userControl.GetValue(CommandProperty) as ICommand;
        }

        private static void OnSetCommandCallback(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)
        {
            var userControl = dependencyObject as UserControl;
            if (userControl != null)
                GetOrCreateBehavior(userControl).Command = e.NewValue as ICommand;
        }

        private static UserControlMouseMoveCommandBehavior GetOrCreateBehavior(UserControl userControl)
        {
            var behavior = userControl.GetValue(UserControlMouseMoveCommandBehaviorProperty) as UserControlMouseMoveCommandBehavior;
            if (behavior == null)
            {
                behavior = new UserControlMouseMoveCommandBehavior(userControl);
                userControl.SetValue(UserControlMouseMoveCommandBehaviorProperty, behavior);
            }

            return behavior;
        }
        
    }
}
